<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Openlayer Tile Map</title>
    <link type="text/css" href="../ol5.3.0/ol.css" rel="stylesheet"/>
    <script type="text/javascript" src="../ol5.3.0/ol.js" charset="utf-8"></script>
    <script type="text/javascript" src="bd09.js" charset="utf-8"></script>
</head>
<body>
<div id="map" style="width: 100%;height:100%"></div>
<script>
    //openlayer 5.3.0版本
    /*定义百度投影，这是实现无偏移加载百度地图离线瓦片核心所在。
    网上很多相关资料在用OpenLayers加载百度地图离线瓦片时都认为投影就是EPSG:3857(也就是Web墨卡托投影)。
    事实上这是错误的，因此无法做到无偏移加载。
    百度地图有自己独特的投影体系，必须在OpenLayers中自定义百度投影，才能实现无偏移加载。
    百度投影实现的核心文件为bd09.js，在迈高图官网可以找到查看这个文件。*/
    var projBD09 = new ol.proj.Projection({
        code: 'BD:09',
        extent: [-20037726.37, -11708041.66, 20037726.37, 12474104.17],
        units: 'm',
        axisOrientation: 'neu',
        global: false
    });
 
    ol.proj.addProjection(projBD09);
    ol.proj.addCoordinateTransforms("EPSG:4326", "BD:09",
        function (coordinate) {
            return lngLatToMercator(coordinate);
        },
        function (coordinate) {
            return mercatorToLngLat(coordinate);
        }
    );
 
    /*定义百度地图分辨率与瓦片网格*/
    var resolutions = [];
    for (var i = 0; i <= 18; i++) {
        resolutions[i] = Math.pow(2, 18 - i);
    }
 
    var tilegrid = new ol.tilegrid.TileGrid({
        origin: [0, 0],
        resolutions: resolutions
    });
 
    /*加载百度地图离线瓦片不能用ol.source.XYZ，ol.source.XYZ针对谷歌地图（注意：是谷歌地图）而设计，
    而百度地图与谷歌地图使用了不同的投影、分辨率和瓦片网格。因此这里使用ol.source.TileImage来自行指定
    投影、分辨率、瓦片网格。*/
    var source = new ol.source.TileImage({
        projection: "BD:09",
        tileGrid: tilegrid,
        tileUrlFunction: function (tileCoord, pixelRatio, proj) {
//openlayer5的版本
            var z = tileCoord[0];
            var x = tileCoord[1];
            var y = tileCoord[2];
// return "http://192.168.1.13:8080/mapImg/2/V1/"+z+"/"+x+"/"+y+".png";
//return 'tiles/' + z + '/' + x + '/' + y + '.png';
            return "http://maponline0.bdimg.com/tile/?qt=vtile&x=" + x + "&y=" + y + "&z=" + z + "&styles=pl&scaler=1&udt=20210506&from=jsapi3_0";
 
            //openlayers6的版本
            //let z = tileCoord[0];
// let x = tileCoord[1];
//let y = -tileCoord[2]-1;
// if(x<0)  x = "M"+(-x);
            // if(y<0) y = "M"+(-y);
        }
    });
 
    var mapLayer = new ol.layer.Tile({
        source: source
    });


    var center = ol.proj.transform([120.29914, 30.20354], 'EPSG:4326', 'BD:09') //把EPSG:4326坐标转为BD09坐标
    console.log(center);
    var map = new ol.Map({
        layers: [
            mapLayer
        ],
        view: new ol.View({
            center: center,
            projection: 'BD:09',
            zoom: 14
        }),
        target: 'map'
    });
  

    var extent = [center[0]- 1080/2, center[1]-1920/2, center[0]+1080/2, center[1]+1920/2];
    // 加载pic1.png照片到地图
    map.addLayer(new ol.layer.Image({
        source: new ol.source.ImageStatic({
            url: 'pic1.jpg', // 熊猫基地地图
            imageExtent: extent     // 映射到地图的范围
        })
    }));
    ///=====================================================================

    const lon = [120.29914,120.29814]
    const lat = [30.20354,30.20454]
    var features = new Array(lon.length);
    for (var i = 0; i < lon.length; i++) {
        // var coordinate = ol.proj.transform([lat[i], lon[i]], 'EPSG:4326', 'EPSG:3857');
        //  var coordinate = ol.proj.transform([lat[i], lon[i]], 'EPSG:4326', 'EPSG:4326');
        
        var coordinate =  ol.proj.transform([lon[i], lat[i] ], 'EPSG:4326', 'BD:09')
        // coordinate.map(parseFloat);
        //  console.log("转换后经纬度：" + coordinate);


        var attr = {
            lat: lat[i],
            lon: lon[i],
        };
        features[i] = new ol.Feature({
            geometry: new ol.geom.Point(coordinate),
            attribute: attr,

        });
    }

    var source = new ol.source.Vector({
        features: features,

    });
    var clusterSource = new ol.source.Cluster({
        distance: 40,
        source: source,

    });

    //加载聚合标注的矢量图层
    var styleCache = {};
    var layerVetor = new ol.layer.Vector({
        source: clusterSource,
        style: function(feature, resolution) {
            var size = 3;
            var style = styleCache[size];
            if (!style) {
                style = [new ol.style.Style({
                    image: new ol.style.Icon( /** @type {olx.style.IconOptions} */ ({
                        anchor: [0.5, 48],
                        anchorOrigin: 'top-right',
                        anchorXUnits: 'fraction',
                        anchorYUnits: 'pixels',
                        offsetOrigin: 'top-right',
                        offset: [0, 1], //偏移量设置
                        scale: 1.2, //图标缩放比例
                        opacity: 1, //透明度
                        src: 'https://openlayers.org/en/v4.6.5/examples/data/icon.png' //图标的url
                    })),
                    text: new ol.style.Text({
                        font: '12px Calibri,sans-serif',
                        text: size.toString(),
                        fill: new ol.style.Fill({
                            color: '#000',
                            border: 5,
                            width: 3
                        })
                    }),
                    anchor: [0.5, 1]    // 设置图标位置
                })];
                styleCache[size] = style;
            }
            return style;
        }
    });
    map.addLayer(layerVetor);


    var source2 = new ol.source.Vector({
        features: [new ol.Feature({
            geometry: new ol.geom.Point(center),
        })],
    });
    var layer2 = new ol.layer.Vector({
        source: source2
    }); 
    map.addLayer(layer2)

</script>
</body>
</html>